package com.celeste.mcpserverfeishu.util;

import com.celeste.mcpserverfeishu.dto.block.CreateBlockResponse;
import com.celeste.mcpserverfeishu.dto.document.CreateDocumentResponse;
import com.celeste.mcpserverfeishu.service.FeishuService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 飞书文档助手工具类
 * 提供便捷的方法来操作飞书文档
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class FeishuDocumentHelper {

    private final FeishuService feishuService;

    /**
     * 创建文档并添加内容
     *
     * @param accessToken 访问令牌
     * @param title 文档标题
     * @param content 文档内容
     * @return 文档ID
     */
    public String createDocumentWithContent(String accessToken, String title, String content) {
        try {
            // 创建文档
            CreateDocumentResponse.Document document = feishuService.createDocument(accessToken, title, "");
            String documentId = document.getDocument_id();
            log.info("已创建文档: {}, ID: {}", title, documentId);
            
            // 添加内容
            if (content != null && !content.isEmpty()) {
                CreateBlockResponse.Block block = feishuService.addTextToDocument(accessToken, documentId, content);
                log.info("已添加内容块, ID: {}", block.getBlock_id());
            }
            
            return documentId;
        } catch (Exception e) {
            log.error("创建文档并添加内容失败", e);
            throw new RuntimeException("创建文档并添加内容失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 读取文档内容
     *
     * @param accessToken 访问令牌
     * @param documentId 文档ID
     * @return 文档内容
     */
    public String readDocument(String accessToken, String documentId) {
        try {
            String content = feishuService.getDocumentContent(accessToken, documentId);
            log.info("已读取文档内容, ID: {}", documentId);
            return content;
        } catch (Exception e) {
            log.error("读取文档内容失败", e);
            throw new RuntimeException("读取文档内容失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 追加内容到文档
     *
     * @param accessToken 访问令牌
     * @param documentId 文档ID
     * @param content 要追加的内容
     */
    public void appendContent(String accessToken, String documentId, String content) {
        try {
            CreateBlockResponse.Block block = feishuService.addTextToDocument(accessToken, documentId, content);
            log.info("已追加内容到文档, 文档ID: {}, 块ID: {}", documentId, block.getBlock_id());
        } catch (Exception e) {
            log.error("追加内容到文档失败", e);
            throw new RuntimeException("追加内容到文档失败: " + e.getMessage(), e);
        }
    }
} 